package com.imooc.controller;

import com.imooc.constants.PassWordConstants;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.UserBO;
import com.imooc.service.UserService;
import com.imooc.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author Administrator
 */
@Api(value = "注册登录", tags = {"用于注册登录的相关接口"})
@RestController
@RequestMapping({"/user"})
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "设置redis值和键", notes = "设置redis值和键", httpMethod = "GET")
    @GetMapping("/set")
    public void set(String key, String values) {
        redisOperator.set(key, values);
    }

    @ApiOperation(value = "获取redis值", notes = "获取redis值", httpMethod = "GET")
    @GetMapping("/get")
    public String get(String key) {
        return redisOperator.get(key);
    }

    @ApiOperation(value = "删除redis值", notes = "删除redis值", httpMethod = "GET")
    @GetMapping("/del")
    public void del(String key) {
        redisOperator.del(key);
    }

    @ApiOperation(value = "用户名是否存在", notes = "用户名是否存在", httpMethod = "GET")
    @GetMapping("/queryUserNameIsExist")
    public IMOOCJSONResult queryUserNameIsExist(@RequestParam String username) {
        // 1. 判断用户名不能为空,为空则报错
        if (StringUtils.isBlank(username)) {
            return IMOOCJSONResult.errorMsg("用户名不能为空");
        }
        // 2. 查询用户在数据库中是否存在，存在则报错
        boolean isExist = userService.queryUserNameIsExist(username);
        if (isExist) {
            return IMOOCJSONResult.errorMsg("用户名已存在");

        }
        // 3. 其余情况都是没有的情况，可以进行新增
        return IMOOCJSONResult.ok("用户名不存在,可以进行新增用户");
    }

    @ApiOperation(value = "用户注册", notes = "用户注册", httpMethod = "POST")
    @PostMapping("/register")
    public IMOOCJSONResult insertUser(@RequestBody UserBO userBO,
                                      HttpServletRequest request,
                                      HttpServletResponse response) {

        String username = userBO.getUsername();
        String password = userBO.getPassword();
        String confirmPassword = userBO.getConfirmPassword();

        // 1. 判断用户名和密码不为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(confirmPassword)) {
            return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }
        // 2. 查询用户名是否存在
        boolean isExist = userService.queryUserNameIsExist(username);
        if (isExist) {
            return IMOOCJSONResult.errorMsg("用户名已存在");
        }
        // 3. 校验密码不能小于6位
        if (password.length() < PassWordConstants.SIX) {
            return IMOOCJSONResult.errorMsg("密码不能小于六位");
        }
        // 4. 确认密码是否一致
        if (!password.equals(confirmPassword)) {
            return IMOOCJSONResult.errorMsg("两次密码不一致");
        }
        // 5. 实现注册
        Users users = userService.insertUser(userBO);

        // 5. 设置敏感信息
        Users registerUser = setNullProperty(users);

        // 6.设置cookie信息
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(registerUser), true);

        // 7. 返回注册后的用户id，便于前端做校验
        return IMOOCJSONResult.ok(registerUser.getId());
    }

    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
    @PostMapping("/login")
    public IMOOCJSONResult login(@RequestBody UserBO userBO,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        String username = userBO.getUsername();
        String password = userBO.getPassword();

        // 1. 判断用户名和密码不为空|
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }
        // 2. 查询用户名是否存在
        Users loginUser = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));
        if (Objects.isNull(loginUser)) {
            return IMOOCJSONResult.errorMsg("用户名或密码不正确");
        }
        // 设置cookie
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(loginUser), true);
        // 3. 登录用户信息
        return IMOOCJSONResult.ok(setNullProperty(loginUser));
    }

    @ApiOperation(value = "用户登出", notes = "用户登出", httpMethod = "POST")
    @PostMapping("/logout")
    public IMOOCJSONResult logout(@RequestParam String usersId,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {
        // 删除cookie
        CookieUtils.deleteCookie(request, response, FOODIE_SHOP_CART);

        /// TODO 后面会完善退出购物车和分布式会话
        return IMOOCJSONResult.ok(usersId);
    }

    //************************************************** 私有方法 ***********************************************//

    /**
     * 设置敏感信息
     */
    private Users setNullProperty(Users userResult) {
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setEmail(null);
        userResult.setCreatedTime(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);
        return userResult;
    }


}